use crate::{helpers::Bot, keyboards::standart_keyboard};
use anyhow::{Result, Context};
use db::{ /*models::MatrixOrTelegramId,*/ Db};
use teloxide::{prelude::*, utils::markdown::{escape_link_url, escape}, types::MessageEntityKind};
use uuid::Uuid;

pub async fn archive(bot: Bot, q: CallbackQuery, data: &str, db: Db) -> Result<()> {
    let user_id = q.from.id;
    // let user = get_user_id(&MatrixOrTelegramId::TelegramId { id: user_id, username: None }, &db).await.context("failed to get user_id")?;
    println!("{data}");
    let post_id = Uuid::parse_str(data)?;
    db.archive_post(post_id).await.context("failed to archive post")?;
    let is_favorite = db.is_favorite(&post_id).await?;
    let message = q.message.clone().unwrap();
    let message_id = message.id;
    let entities = message.entities().unwrap();
    let text = message.text().unwrap();
    let chat_id = message.chat.id;
    bot.answer_callback_query(q.id).text("Archived!").await?;
    // let answer = {
    // //    let mut answer = text;
    //    let mut has_text_link = false;
    //    let mut offset;
    //    let mut length = 0;
    //         for i in entities {
    //             println!("{:#?}", i);
    //             match &i.kind{
    //             MessageEntityKind::TextLink { url } =>{
    //                 has_text_link = true
    //             }
    //             MessageEntityKind::Url => {
    //                 offset = i.offset;
    //                 length = i.length;
    //             }
    //             _ => {}
    //         }
    //     }
    //         if !has_text_link {
    //             let (link, service_text) = text.split_at(length);

    //         format!(r"{}{} \[Archived\]", &escape(&escape_link_url(link)), escape(service_text))
    //         } else{
    //         escape(&format!("{} [Archived]", text))
    //         }
    //    };

    // let text = escape(&format!("{} [Archived]", escape_link_url(q.message.clone().unwrap().text().unwrap())));
    // println!("{text}");
    // bot.edit_message_text(
    //     chat_id,
    //     message_id,
    //     answer,
    // )
    // .entities(entities.to_owned()) //.map(|entities| entities.to_owned().into_iter()))
    // .reply_markup(standart_keyboard(data, true, is_favorite))
    // .await?;
    bot.edit_message_reply_markup(chat_id, message_id)
        .reply_markup(standart_keyboard(data, true, is_favorite))
        // .parse_mode(MarkdownV2)
        .await?;
    Ok(())
}
